<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    wrapClassName="j-user-select-modal"
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="取消"
  >
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <a-col :md="6" :sm="24">
        <a-card :bordered="false">
          <!--组织机构-->
          <a-directory-tree
           style="height: 398px; overflow: auto"
            selectable
            :selectedKeys="selectedDepIds"
            :checkStrictly="true"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="departTree"
            :expandAction="false"
            :expandedKeys.sync="expandedKeys"
            @select="onDepSelect"
          />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <a-card :bordered="false">
          关键字:
          <a-input-search
            :style="{width:'250px',marginBottom:'15px'}"
            placeholder="账号/姓名/手机号"
            v-model="queryParam.keyword"
            @search="onSearch"
          ></a-input-search>
          <a-button @click="loadData(1)" type="primary" style="margin-left: 20px">查询</a-button>
          <a-button @click="searchReset(1)" type="primary" style="margin-left: 20px">重置</a-button>
          <!--用户列表-->
          <a-table
            ref="table"
            :scroll="{ y: 250 }"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            @change="handleTableChange">
          </a-table>
          <div style="display: inline-block">
            <span style="margin-left: 8px">
              {{ `已选 ${selectedRowKeys.length}/${ipagination.total} 条` }}
            </span>
          </div>
          <div style="display: inline-block; float: right">
            <a-pagination
              :total="ipagination.total"
              v-model="ipagination.current"
              :page-size-options="ipagination.options"
              :page-size="ipagination.pageSize"
              @change="onChangePage"
              @showSizeChange="onChangePage"
              show-quick-jumper
              show-size-changer
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </j-modal>
</template>

<script>
  import { pushIfNotExist, filterObj } from '@/utils/util'
  import {queryDepartTreeList, getUserList, queryUserByDepId} from '@/api/api'
  import { getAction } from '@/api/manage'

  export default {
    name: 'JSelectUserByDepJkeModal',
    components: {},
    props: ['modalWidth', 'multi', 'userIds', 'store', 'text', 'limit'],
    data() {
      return {
        queryParam: {
          username: "",
        },
        columns: [
          {
            title: '账号',
            align: 'center',
            dataIndex: 'username'
          },
          {
            title: '姓名',
            align: 'center',
            dataIndex: 'realname'
          },
          // {
          //   title: '性别',
          //   align: 'center',
          //   dataIndex: 'sex',
          //   customRender: function (text) {
          //     if (text === 1) {
          //       return '男'
          //     } else if (text === 2) {
          //       return '女'
          //     } else if (text === 0){
          //       return '未知'
          //     } else {
          //       return text
          //     }
          //   }
          // },
          {
            title: '手机号',
            align: 'center',
            dataIndex: 'phone'
          },
          {
            title: '部门',
            align: 'center',
            dataIndex: 'departNames'
          }
        ],
        scrollTrigger: {},
        dataSource: [],
        selectionRows: [],
        selectedRowKeys: [],
        selectUserRows: [],
        selectUserIds: [],
        title: '选择用户',
        ipagination: {
          current: 1,
          pageSize: 10,
          options: ['10', '20', '30'],
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        selectedDepIds: [],
        departTree: [],
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        expandedKeys: [],
      }
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio';
      }
    },
    watch: {
      userIds: {
        immediate: true,
        handler() {
          this.initUserNames()
        }
      },
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      // this.loadData()
    },
    methods: {
      initUserNames() {
        if (this.userIds) {
          // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
          let values = this.userIds.split(',') + ','
          let param = {[this.store]: values}
          getAction('/sys/user/getMultiUser', param).then((list)=>{
            this.selectionRows = []
            let selectedRowKeys = []
            let textArray = []
            if(list && list.length>0){
              for(let user of list){
                textArray.push(user[this.text])
                selectedRowKeys.push(user['id'])
                this.selectionRows.push(user)
              }
            }
            this.selectedRowKeys = selectedRowKeys
            this.$emit('initComp', textArray.join(','))
          })

        } else {
          // JSelectUserByDep组件bug issues/I16634
          this.$emit('initComp', '')
          // 前端用户选择单选无法置空的问题 #2610
          this.selectedRowKeys = []
        }
      },
      async loadData(arg, num) {
        let url = '/sys/user/queryUserByDepId'
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        let params = this.getQueryParams()//查询条件
        // if (!params.departId) {
        //   url = '/sys/user/queryUserByTenantId'
        // }
        this.loading = true
        getAction(url, {tenantId: this.$store.getters.tenantid, ...params}).then(res=>{
          if (res.success) {
            this.dataSource = res.result
            this.ipagination.total = res.total
          }
        }).finally(() => {
          this.loading = false
        })
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      },
      showModal() {
        this.visible = true;
        this.queryDepartTree();
        this.initUserNames()
        this.loadData();
        this.form.resetFields();
      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        if (this.selectedDepIds.length>0) {
          param.id = this.selectedDepIds.join(',')
        } else if (this.departTree.length>0) {
          param.id = this.departTree[0].id
        }
        // param.id = this.selectedDepIds.join(',')
        return filterObj(param);
      },
      getQueryField() {
        let str = 'id,';
        for (let a = 0; a < this.columns.length; a++) {
          str += ',' + this.columns[a].dataIndex;
        }
        return str;
      },
      searchReset(num) {
        let that = this;
        that.selectedRowKeys = [];
        that.selectUserIds = [];
        that.selectedDepIds = [];
        if (num !== 0) {
          that.queryParam = {};
          that.loadData(1);
        }
      },
      close() {
        this.searchReset(1);
        this.visible = false;
        this.$emit('close')
      },
      // 分页
    onChangePage(current, pageSize) {
      this.ipagination.current = current
      this.ipagination.pageSize = pageSize
      this.loadData()
    },
      handleTableChange(pagination, filters, sorter) {
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc';
        }
        this.ipagination = pagination;
        this.loadData();
      },
      handleSubmit() {
        let that = this;
        this.getSelectUserRows();
        that.$emit('ok', that.selectUserRows);
        that.searchReset()
        that.close();
      },
      //获取选择用户信息
      getSelectUserRows() {
        this.selectUserRows = []
        for (let row of this.selectionRows) {
          if (this.selectedRowKeys.includes(row.id)) {
            this.selectUserRows.push(row)
          }
        }
        this.selectUserIds = this.selectUserRows.map(row => row.username).join(',')
      },
      // 点击树节点,筛选出对应的用户
      onDepSelect(selectedDepIds) {
        if (selectedDepIds[0] != null) {
          if (this.selectedDepIds[0] !== selectedDepIds[0]) {
            this.selectedDepIds = [selectedDepIds[0]];
          }
          this.loadData(1);
        }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        if (this.limit !== 0) {
          if (selectedRowKeys && selectedRowKeys.length <= this.limit) {
            this.selectedRowKeys = selectedRowKeys;
            selectionRows.forEach(row => pushIfNotExist(this.selectionRows, row, 'id'))
          } else {
            this.$antdMessage.error('最多可选' + this.limit + '人')
          }
        } else {
          this.selectedRowKeys = selectedRowKeys;
          selectionRows.forEach(row => pushIfNotExist(this.selectionRows, row, 'id'))
        }
      },
      onSearch() {
        this.loadData(1);
      },
      // 根据选择的id来查询用户信息
      initQueryUserByDepId(selectedDepIds) {
        this.loading = true
        return queryUserByDepId({id: selectedDepIds.toString()}).then((res) => {
          if (res.success) {
            this.dataSource = res.result;
            this.ipagination.total = res.result.length;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      queryDepartTree() {
        queryDepartTreeList({tenantId: this.$store.getters.tenantid}).then((res) => {
          if (res.success) {
            this.departTree = res.result.list || res.result;
            this.loadData()
            // 默认展开父节点
            this.expandedKeys = this.departTree.map(item => item.id)
          }
        })
      },
      modalFormOk() {
        this.loadData();
      }
    }
  }
</script>

<style scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>